<template>
  <form-template
    class="form"
    v-model:form="form"
    labelWidth="7.25em"
    :options="options"
    :loading="loading"
    @uploadOk="onUploadOk"
    @submit="onSubmit"
  ></form-template>
</template>

<script setup>
  const router = useRouter()
  const route = useRoute()
  const loading = ref(false)
  const detailId = ref()
  const form = ref({})
  const options = ref([
    {
      label: '原证照保管单位',
      key: 'origCustodyUnit',
      type: 'field',
      disabled: true,
      rules: [{required: true, message: '请选择原证照保管单位'}],
    },
    {
      label: '新证照保管单位',
      key: 'custodyUnit',
      type: 'picker',
      columns: [],
      filter: true,
      rules: [
        {
          validator: val => {
            return Boolean(val !== form.value.origCustodyUnit)
          },
          message: `归还日应在借用开始时间${form.value.borrowingStartDate?.split(' ')[0]}之后`,
        },
        {required: true, message: '请选择新证照保管单位'},
      ],
    },
    {label: '证照号码', key: 'certNumber', type: 'field', disabled: true},
    {label: '转移事由', key: 'transferReason', type: 'textarea', rules: [{required: true, message: '请填写转移事由'}]},
    {label: '附件', key: 'attachmentUrl', type: 'upload', accept: ''},
  ])
  let fileList = []
  let unitColumns = []
  watch(
    () => form.value.custodyUnitKeyWord,
    kw => {
      const custodyUnitItem = options.value.find(item => item.key === 'custodyUnit')
      if (kw?.length > 0) {
        custodyUnitItem.columns = unitColumns.filter(item => item.text.includes(kw))
      } else {
        custodyUnitItem.columns = unitColumns
      }
    }
  )
  const onUploadOk = list => {
    fileList = list
  }
  const onSubmit = () => {
    const params = {
      ...form.value,
      custodyUnitId: form.value.custodyUnitValue,
      attachmentUrl: fileList.attachmentUrl.map(item => item.url).join(','),
    }
    delete params.id
    delete params.createBy
    delete params.createTime
    delete params.updateBy
    delete params.updateTime
    delete params.deleted
    delete params.custodyUnitValue
    loading.value = true
    const loadingToast = showLoadingToast({
      duration: 500,
      message: '申请中...',
      forbidClick: true,
      loadingType: 'spinner',
    })
    $post('/api/v1/cert/transfer/record', params)
      .then(() => {
        showSuccessToast('申请成功')
        router.replace({path: '/'})
      })
      .finally(() => {
        loading.value = false
        loadingToast.close()
      })
  }
  const onLoad = id => {
    showLoadingToast({
      duration: 500,
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
    })
    $get('/bus/api/v1/department/system/grade', {depType: 2}).then(res => {
      const {data} = res
      const custodyUnitItem = options.value.find(item => item.key === 'custodyUnit')
      const replaceData = data.map(item => {
        return {
          text: item.depName,
          value: item.depId,
          parent: item.parentId,
        }
      })
      // const rootData = replaceData.filter(item => !item.parent)
      // custodyUnitItem.columns = recursionTree(rootData, replaceData)
      custodyUnitItem.columns = replaceData
      unitColumns = replaceData
    })
    $get(`/api/v1/cert/info/${detailId.value}`)
      .then(res => {
        const {data} = res
        form.value = {
          ...data,
          origCustodyUnit: data.custodyUnit,
          origCustodyUnitId: data.custodyUnitId,
          custodyUnit: undefined,
          custodyUnitId: undefined,
        }
      })
      .finally(() => {
        closeToast()
      })
  }
  onMounted(() => {
    detailId.value = route.query?.id
    if (detailId.value) onLoad()
  })
</script>

<style scoped>
  .form {
    margin-top: 32px;
  }
</style>
